<?php

namespace App\Http\Resources;

use App\Helpers\BaseResource;

class DocArticle extends BaseResource
{

    public function toArray($request)
    {
        if ($this->rs_type == 'node-edit') {
            return $this->nodeEdit();
        }
        return $this->filterFields([
            'id' => hashid_encode($this->id),
            'title' => $this->title,
            'cover' => \App\Models\DocArticle::getCover($this),
            'abstract' => str_limit(\App\Models\DocArticle::getText($this)),
            'created' => (string)$this->created_at,
            'mode' => (string)$this->mode,
            'status' => $this->status ?? 1,
            'updated_format' => $this->updated_at->diffForHumans(),
            'is_try' => (boolean)$this->is_try,
            'link' => urlencode(config('wx.web_host') . 'article-page?id=' . hashid_encode($this->id)),
            'user' => $this->whenLoaded('user', function () {
                $userRes = User::make($this->user);
                $userRes = $this->get_relate_data('user', $userRes);
                return $userRes;
            }),
            'content' => $this->when($this->ckFields('content'), function () {
                if ($this->mode == 'node') {
                    return [
                        'node' => \App\Models\DocArticle::getNodeContent($this),
                        'images' => \App\Models\DocArticle::getNodeImages($this)
                    ];
                }
            }),
            'share_data' => \App\Models\DocArticle::getShareData($this, $this->getUser()),
            'likers_count' => $this->whenLoaded('likers', function () {
                return collect($this->likers)->count();
            })
        ]);
    }

    private function nodeEdit()
    {
        return [
            'id' => hashid_encode($this->id),
            'title' => $this->title,
            'cover' => $this->cover,
            'content' => \App\Models\DocArticle::getContent($this),
        ];
    }
}
